<?php

/**
 * Description of WebserviceBase
 *
 * @author bonfiglio
 * @todo Commenter !!!
 */
abstract class WebserviceBase {

    public static $defaultOptions = array('errors' => array(), 'post' => array());
    protected $headerXml = "<?xml version='1.0'?>";
    protected $name = false;
    protected $post = array();     //Données renvoyées par le client
    protected $errors = array();    //Erreur(s) à renvoyer au client

    final public function __construct($options = array()) {
        $options = array_merge(self::$defaultOptions, $options);

        $this->name = $options['name'];

        $this->errors = $options['errors'];

        $this->post = $options['post'];

        $this->output = $options['post']['format-output'];

        if (count($this->errors)) {
            $this->sendContent($this->errors, 'erreurs trouvées', 'red');
        }
    }

    protected function sendContent($content) {
        if ($this->output == 'xml') {
            Page::sendXml($this->headerXml.$content);
        } elseif (is_string($content)) {
            $SimpleXMLElement = simplexml_load_string($this->headerXml.$content);
            Page::sendJson($SimpleXMLElement);
        }elseif ($this->output == 'json') {
            echo json_encode($content);
        } else {
            Log::pre($content, 'STOP');
//            echo json_encode($content);
        }
        exit;
    }

    protected function setXmlContent($fields, $data, $matchingKeys = array()) {
            $content = '';
            foreach ($fields as $field => $attributs) {
                $name = isset($matchingKeys[$field]) ? $matchingKeys[$field] : $field;
                $value = isset($data[$field]) && strlen($data[$field]) ? $data[$field] : '';
                $content .= HtmlTag::$name($value);
            }
            return $content;
    }

    abstract protected function answer();
}

?>
